<?php

// +----------------------------------------------------------------------
// | tpadmin [a web admin based ThinkPHP5]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 tianpian All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: tianpian <tianpian0805@gmail.com>
// +----------------------------------------------------------------------
//------------------------
// 助手函数
//-------------------------

/**
 * 对ID加密
 * @param null|int $length
 * @param null|string $salt
 * @param null|string $alphabet
 * @return Hashids\Hashids static
 */
function hashids($length = null, $salt = null, $alphabet = null) {
    return \Hashids\Hashids::instance($length, $salt, $alphabet);
}

/**
 * 一键导出Excel 2007格式
 * @param array $header     Excel头部 ["COL1","COL2","COL3",...]
 * @param array $body       和头部长度相等字段查询出的数据就可以直接导出
 * @param null|string $name 文件名，不包含扩展名，为空默认为当前时间
 * @param string|int $version 版本 2007|2003|ods|pdf
 * @return string
 */
function export_excel($header, $body, $name = null, $version = '2007') {
    return \Excel::export($header, $body, $name, $version);
}

/**
 * 获取七牛上传token
 * @return mixed
 */
function qiniu_token() {
    return \Qiniu::token();
}

/**
 * 检查指定节点是否有权限
 * @param null $action
 * @param null $controller
 * @param null $module
 * @return bool
 */
function check_access($action = null, $controller = null, $module = null) {
    return \Rbac::AccessCheck($action, $controller, $module);
}

/**
 * 文件下载
 * @param $file_path
 * @param string $file_name
 * @param string $file_size
 * @param string $ext
 * @return string
 */
function download($file_path, $file_name = '', $file_size = '', $ext = '') {
    return \File::download($file_path, $file_name, $file_size, $ext);
}

function fieldRegex($value, $rule) {
    $validate = array(
        'require' => '/.+/',
        'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
        'mobile' => '/^(13|15|14|17|18)\d{9}$/',
        'tel' => '/^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$/',
        'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
        'currency' => '/^\d+(\.\d+)?$/',
        'number' => '/^\d+$/',
        'zip' => '/^\d{6}$/',
        'integer' => '/^[-\+]?\d+$/',
        'double' => '/^[-\+]?\d+(\.\d+)?$/',
        'english' => '/^[A-Za-z]+$/',
        'img' => '(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/',
        'in' => '/^(\d{1,10},)*(\d{1,10})$/',
        'qq' => '/^[1-9]*[1-9][0-9]*$/'
    );
// 检查是否有内置的正则表达式
    if (isset($validate[strtolower($rule)]))
        $rule = $validate[strtolower($rule)];
    return preg_match($rule, $value) === 1;
}

//过滤XSS攻击
function reMoveXss($val) {
    $val = preg_replace('/([\x00-\x08])/', '', $val);
    $val = preg_replace('/([\x0b-\x0c])/', '', $val);
    $val = preg_replace('/([\x0e-\x19])/', '', $val);
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
        $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
    }

    $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'base');
    $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);
    $found = true;
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
            $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
            if ($val_before == $val) {
                $found = false;
            }
        }
    }
    return $val;
}

/**
 * 安全过滤数据
 * @param string	$str		需要处理的字符或数组
 * @param string	$type		返回的字符类型，支持，string,int,float,html
 * @param mixed		$default	当出现错误或无数据时默认返回值
 * @return 		mixed		当出现错误或无数据时默认返回值
 */
function getStr($str, $type = 'string', $default = '') {
    //如果为空则为默认值
    if ($str === '')
        return $default;
    if (is_array($str)) {
        $_str = array();
        foreach ($str as $key => $val) {
            $_str[$key] = getStr($val, $type, $default);
        }
        return $_str;
    }
    //转义
    if (!get_magic_quotes_gpc())
        $str = addslashes($str);
    switch ($type) {
        case 'string': //字符处理
            $_str = strip_tags($str);
			$_str = str_replace("&rdquo;", '”', $_str);
			$_str = str_replace("&ldquo;", '“', $_str);
            $_str = str_replace("'", '&#39;', $_str);
            $_str = str_replace("\"", '&quot;', $_str);
            $_str = str_replace("\\", '', $_str);
            $_str = str_replace("\/", '', $_str);
            $_str = str_replace("+/v", '', $_str);
			$_str = urldecode($_str);
			$_str = str_ireplace(array('!','@','#','$','^','&',' ','\r','\n','\r\n'), '', $_str);
            break;
        case 'int': //获取整形数据
            $_str = intval($str);
            break;
        case 'float': //获浮点形数据
            $_str = floatval($str);
            break;
        case 'html': //获取HTML，防止XSS攻击
            $_str = reMoveXss($str);
            break;
        default: //默认当做字符处理
            $_str = strip_tags($str);
    }

    return $_str;
}

function addLog($msg, $file = 'newexam_error.log', $dir = '/var/log/gandianli/dberror/') {
    $file = $dir . $file . '.' . date('Y-m-d');
    if ((is_dir($dir) || @mkdir($dir, 0755, true)) && is_writable($dir)) {
        $data = 'Date:' . date('Y-m-d H:i:s') . ' ' . $msg . "\n";
        $f = fopen($file, 'a+');
        fwrite($f, $data, strlen($data));
        fclose($f);
        return true;
    }
    return false;
}
